package cn.lili.modules.order.order.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.order.order.entity.dos.*;
import cn.lili.modules.order.order.entity.dto.RankingAwardDetailsDTO;
import cn.lili.modules.order.order.entity.dto.TopUserDTO;
import cn.lili.modules.order.order.mapper.RankingAwardDetailsMapper;
import cn.lili.modules.order.order.service.*;
import cn.lili.modules.system.client.LogisticsClient;
import cn.lili.modules.system.constants.DictConstant;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 排名奖品领取明细 服务实现类
 * </p>
 *
 * @author zhushiqing
 * @since 2023-12-21
 */
@Service
@Slf4j
@AllArgsConstructor(onConstructor_ = @Lazy)
public class RankingAwardDetailsServiceImpl extends ServiceImpl<RankingAwardDetailsMapper, RankingAwardDetails> implements IRankingAwardDetailsService {

    private IRankingActivityConfigService activityConfigService;

    private IRankingScoreDetailsService rankingScoreDetailsService;

    private LogisticsClient logisticsClient;

    private IRankingGrowAwardStatusService rankingGrowAwardStatusService;

    private IRankingGrowAwardConfigService rankingGrowAwardConfigService;

    private IRankingDistributionService rankingDistributionService;

    /**
     * 根据dto查询排名奖品领取明细
     *
     * @param dto
     * @return
     */
    @Override
    public List<RankingAwardDetails> selectListByDto(RankingAwardDetailsDTO dto) {
        LambdaUpdateWrapper<RankingAwardDetails> query = new LambdaUpdateWrapper();
        if (CollUtil.isNotEmpty(dto.getUserIds())) {
            query.in(RankingAwardDetails::getUserId, dto.getUserIds());
        }
        if (null != dto.getActivityId()) {
            query.eq(RankingAwardDetails::getActivityId, dto.getActivityId());
        }
        query.eq(RankingAwardDetails::getDeleteFlag, Boolean.FALSE);
        return baseMapper.selectList(query);
    }

    /**
     * 领取排名奖励
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void claimThePrize(RankingAwardDetails rankingAwardDetails) {
        //参数校验
        RankingActivityConfig currentActivity = this.check(rankingAwardDetails);
        //获取当前用户所属排名 =》 领取对应排名的奖品
        List<TopUserDTO> topUserDTOList = rankingScoreDetailsService.topUser(currentActivity, currentActivity.getCommissCondition().doubleValue(), DictConstant.SCORE_ORDER_STATUS_02);
        //当前排名
        Integer currentIndex = null;
        for (int i = 0; i < topUserDTOList.size(); i++) {
            TopUserDTO topUserDTO = topUserDTOList.get(i);
            if (topUserDTO.getUid().equals(UserContext.getCurrentId())) {
                currentIndex = i;
                break;
            }
        }
        if (currentIndex == null) {
            throw new ServiceException("您当前无排名");
        }
        currentIndex = currentIndex + 1;
        LambdaQueryWrapper<RankingAwardDetails> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.eq(RankingAwardDetails::getUserId, UserContext.getCurrentId());
        detailsLambdaQueryWrapper.eq(RankingAwardDetails::getActivityId, currentActivity.getId());
        detailsLambdaQueryWrapper.eq(RankingAwardDetails::getAwardStatus, DictConstant.AWARD_STATUS_0);
        RankingAwardDetails awardDetails = super.getOne(detailsLambdaQueryWrapper);
        if (awardDetails == null) {
            log.error("未获取到，待领奖信息 == {},==== , {} , {}", currentActivity.getId(), UserContext.getCurrentId(), currentIndex);
            throw new ServiceException("未获取到，待领奖信息");
            //            //当前排名领取的奖品
//            RankingAwards currentAwards = null;
//            List<RankingAwards> awardsByActivity = rankingAwardsService.getAwardsByActivity(currentActivity.getId());
//            if (CollectionUtil.isNotEmpty(awardsByActivity)) {
//                //当前排名，小于 最大可领奖人 （例如： 排名5，  可领奖人 1~3,4~6,7~9），则可领奖
//                for (RankingAwards rankingAwards : awardsByActivity) {
//                    Integer startRank = rankingAwards.getRankingMin();
//                    Integer endRank = rankingAwards.getRankingMax();
//                    // 判断当前排名是否在奖励规则范围内
//                    if (currentIndex >= startRank && currentIndex <= endRank) {
//                        //可以领取奖品
//                        currentAwards = rankingAwards;
//                        break;
//                    }
//                }
//            }
//            if (currentAwards == null) {
//                log.error("未获取到，当前可领奖的奖品信息 {} == {}", JSONObject.toJSONString(awardsByActivity), currentIndex);
//                throw new ServiceException("未获取到，当前可领奖的奖品信息");
//            }
//            //生成领奖信息
//            this.createAwardDetail(currentActivity, currentAwards, rankingAwardDetails);
//            return;
        }
        //填写领用信息，并将状态修改为，已领取
        awardDetails.setDeliveryName(rankingAwardDetails.getDeliveryName());
        awardDetails.setDeliveryPhone(rankingAwardDetails.getDeliveryPhone());
        awardDetails.setDeliveryAddress(rankingAwardDetails.getDeliveryAddress());
        awardDetails.setAwardStatus(DictConstant.AWARD_STATUS_1);
        super.updateById(awardDetails);
    }

    /**
     * 创建排名领奖信息
     */
    private void createAwardDetail(RankingActivityConfig currentActivity, RankingAwards currentAwards, RankingAwardDetails awardDetails) {
        AuthUser authUser = UserContext.getCurrentUser();
        //查询当前用户是否能入围排名
        LambdaQueryWrapper<RankingScoreDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingScoreDetails::getCurrentActivityId, currentActivity.getId());
        queryWrapper.eq(RankingScoreDetails::getParentUserId, UserContext.getCurrentId());
        queryWrapper.ne(RankingScoreDetails::getOrderStatus, DictConstant.SCORE_ORDER_STATUS_03);
        queryWrapper.le(RankingScoreDetails::getCreateTime, currentActivity.getEndDate());
        queryWrapper.ge(RankingScoreDetails::getCreateTime, currentActivity.getStartDate());
        List<RankingScoreDetails> detailsList = rankingScoreDetailsService.list(queryWrapper);
        double unSettleCommiss = detailsList.stream().filter(f -> DictConstant.SCORE_ORDER_STATUS_01.equals(f.getOrderStatus())).map(RankingScoreDetails::getScore).map(BigDecimal::doubleValue).mapToDouble(Double::valueOf).sum();
        double settleCommiss = detailsList.stream().filter(f -> DictConstant.SCORE_ORDER_STATUS_02.equals(f.getOrderStatus())).map(RankingScoreDetails::getScore).map(BigDecimal::doubleValue).mapToDouble(Double::valueOf).sum();

        RankingAwardDetails rankingAwardDetails = RankingAwardDetails.builder()
                .activityId(currentActivity.getId())
                .userId(authUser.getId())
                .nickName(authUser.getNickName())
                .totalScore(BigDecimal.valueOf(settleCommiss).add(BigDecimal.valueOf(unSettleCommiss)))
                .settleCommiss(BigDecimal.valueOf(settleCommiss))
                .unSettleCommiss(BigDecimal.valueOf(unSettleCommiss))
                .rankingAwardId(currentAwards.getId())
                .awardName(currentAwards.getAwardName())
                .awardStatus(DictConstant.AWARD_STATUS_1)
                .deliveryName(awardDetails.getDeliveryName())
                .deliveryPhone(awardDetails.getDeliveryPhone())
                .deliveryAddress(awardDetails.getDeliveryAddress())
                .build();
        super.save(rankingAwardDetails);
    }

    /**
     * 参数校验
     *
     * @param rankingAwardDetails 参数
     */
    private RankingActivityConfig check(RankingAwardDetails rankingAwardDetails) {
        if (StringUtils.isEmpty(rankingAwardDetails.getActivityId())) {
            throw new ServiceException("活动id为空: activityId");
        }
        if (StringUtils.isEmpty(rankingAwardDetails.getDeliveryName())) {
            throw new ServiceException("收件人为空: deliveryName");
        }
        if (StringUtils.isEmpty(rankingAwardDetails.getDeliveryPhone())) {
            throw new ServiceException("收件手机号为空: deliveryPhone");
        }
        if (StringUtils.isEmpty(rankingAwardDetails.getDeliveryAddress())) {
            throw new ServiceException("收货地址为空: deliveryAddress");
        }
        RankingActivityConfig currentActivity = activityConfigService.getById(rankingAwardDetails.getActivityId());
        if (currentActivity == null) {
            log.error("未获取到活动信息 == {}", rankingAwardDetails.getActivityId());
            throw new ServiceException("未获取到活动信息");
        }
        //开始时间，大于当前时间
        if (currentActivity.getStartDate().getTime() > new Date().getTime()) {
            log.error("当前排名活动还未开始");
            throw new ServiceException("当前排名活动还未开始,待活动结束后才可领奖");
        }
        //不等于已结束  &&  结束时间小于当前时间
        if (!DictConstant.ACTIVITY_STATUS_02.equals(currentActivity.getActivityStatus()) && currentActivity.getEndDate().getTime() > new Date().getTime()) {
            log.error("当前排名活动还未结束");
            throw new ServiceException("当前排名活动还未结束,请继续维持排名,待活动结束后即可领奖");
        }

        //判断当前人。能否领取奖品
        LambdaQueryWrapper<RankingScoreDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RankingScoreDetails::getCurrentActivityId, currentActivity.getId());
        queryWrapper.eq(RankingScoreDetails::getOrderStatus, DictConstant.SCORE_ORDER_STATUS_02);
        queryWrapper.eq(RankingScoreDetails::getParentUserId, UserContext.getCurrentId());
        queryWrapper.le(RankingScoreDetails::getCreateTime, currentActivity.getEndDate());
        queryWrapper.ge(RankingScoreDetails::getCreateTime, currentActivity.getStartDate());
        List<RankingScoreDetails> detailsList = rankingScoreDetailsService.list(queryWrapper);
        if (CollectionUtil.isEmpty(detailsList)) {
            throw new ServiceException("当前用户未达到领用奖品条件");
        }
        //是否已经领取过奖品
        LambdaQueryWrapper<RankingAwardDetails> detailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        detailsLambdaQueryWrapper.eq(RankingAwardDetails::getActivityId, currentActivity.getId());
        detailsLambdaQueryWrapper.eq(RankingAwardDetails::getUserId, UserContext.getCurrentId());
        detailsLambdaQueryWrapper.ne(RankingAwardDetails::getAwardStatus, DictConstant.AWARD_STATUS_0);
        if (super.count(detailsLambdaQueryWrapper) > 0) {
            throw new ServiceException("你已领取过该排名奖励");
        }

        //入围排名条件
        RankingDistribution rankingDistribution = rankingDistributionService.getRankingDistribution();
//        double scoreSum = detailsList.stream().map(RankingScoreDetails::getScore).map(BigDecimal::doubleValue).mapToDouble(Double::valueOf).sum();
        BigDecimal commissCondition = currentActivity.getCommissCondition();
        if (rankingDistribution != null && commissCondition.doubleValue() > rankingDistribution.getRebateTotal().doubleValue()) {
            throw new ServiceException("当前用户没有入围排名");
        }

        return currentActivity;
    }


    /**
     * 根据用户id获取排名奖品物流记录
     *
     * @param rankingAwardDetailsId
     * @return
     */
    @Override
    public ResultMessage<Object> getRankingAwardLogisticsById(String rankingAwardDetailsId, Integer queryFrom) {
        //查询成长奖励的物流信息
        if (queryFrom == 1) {
            return rankingGrowAwardConfigService.viewLogistic(rankingAwardDetailsId);
        }
        //查询排名活动的物流信息
        //根据用户id获取排名奖品物流记录
        RankingAwardDetails rankingAwardDetails = baseMapper.selectById(rankingAwardDetailsId);
        if (null == rankingAwardDetails) {
            return ResultUtil.error(400, "未找到该奖品信息");
        }
        String phone = StringUtils.isNotEmpty(rankingAwardDetails.getDeliveryPhone()) ? rankingAwardDetails.getDeliveryPhone().substring(rankingAwardDetails.getDeliveryPhone().length() - 4) : "";
        return ResultUtil.data(logisticsClient.getLogistic(rankingAwardDetails.getExpressName(), rankingAwardDetails.getExpressNo(), phone));
    }

    /**
     * 给排名奖品明细添加运单号
     *
     * @param dto
     * @return
     */
    @Override
    public ResultMessage<Object> addRankingAwardExpressInfo(RankingAwardDetailsDTO dto) {
        //填写成长奖励物流信息
        if (dto.getQueryFrom() == 1) {
            RankingGrowAwardStatus growAwardStatus = new RankingGrowAwardStatus();
            growAwardStatus.setExpressNo(dto.getExpressNo());
            growAwardStatus.setExpressName(dto.getExpressName());
            growAwardStatus.setId(dto.getRankingAwardDetailsId());
            return rankingGrowAwardStatusService.addExpressNoToGrowAward(growAwardStatus);
        }
        //填写排名奖励的物流信息
        //根据用户id获取排名奖品物流记录
        RankingAwardDetails rankingAwardDetails = baseMapper.selectById(dto.getRankingAwardDetailsId());
        if (null == rankingAwardDetails) {
            return ResultUtil.error(400, "未找到该奖品信息");
        }
        rankingAwardDetails.setExpressNo(dto.getExpressNo());
        rankingAwardDetails.setExpressName(dto.getExpressName());
        rankingAwardDetails.setAwardStatus(2);
        if (baseMapper.updateById(rankingAwardDetails) > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }
}
